//
//  QWHttpUtil.m
//  117goFramework
//
//  Created by Yunhai.Wu on 15/7/30.
//  Copyright (c) 2015年 117go. All rights reserved.
//

#import "QWHttpUtil.h"

@implementation QWHttpUtil

+ (NSString *) stringWithFormEncodedComponents:(NSDictionary*) params {
    if ([params count] > 0) {
        NSMutableArray *arguments = [NSMutableArray arrayWithCapacity:[params count]];
        [params enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL *stop) {
            [arguments addObject:[NSString stringWithFormat:@"%@=%@",
                                  [self stringByEscapingForURLQuery:key],
                                  [self stringByEscapingForURLQuery:[object description]]]];
        }];
        return [arguments componentsJoinedByString:@"&"];
    }
    return nil;
}

+ (NSString *)stringByEscapingForURLQuery:(NSString*) key {
    NSString *result = key;
    static CFStringRef leaveAlone = CFSTR(" ");
    static CFStringRef toEscape = CFSTR("\n\r:/=,!$&'()*+;[]@#?%");
    CFStringRef escapedStr = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)key, leaveAlone,
                                                                     toEscape, kCFStringEncodingUTF8);
    if (escapedStr) {
        NSMutableString *mutable = [NSMutableString stringWithString:(__bridge NSString *)escapedStr];
        CFRelease(escapedStr);
        [mutable replaceOccurrencesOfString:@" " withString:@"+" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [mutable length])];
        result = mutable;
    }
    return result;
}


@end
